//
//  ViewController.m
//  OrientationExample
//
//  Created by cjl on 2019/3/29.
//  Copyright © 2019 cjl. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *bt;

@end

@implementation ViewController

- (IBAction)change:(id)sender {
    UIDevice *device = [UIDevice currentDevice];
    UIDeviceOrientation orientation = device.orientation;
    UIDeviceOrientation targetOrientation;
    switch (orientation) {
        case UIDeviceOrientationUnknown:
        case UIDeviceOrientationPortrait:
        case UIDeviceOrientationPortraitUpsideDown:
            targetOrientation = UIDeviceOrientationLandscapeLeft;
            break;
        case UIDeviceOrientationLandscapeLeft:
        case UIDeviceOrientationLandscapeRight:
            targetOrientation = UIDeviceOrientationPortrait;
            break;
        default:
            targetOrientation = UIDeviceOrientationPortrait;
            break;
    }
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if(!appDelegate.allowRotation){
        [self endFullScreen];
    }else{
        [self begainFullScreen];
    }
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = targetOrientation;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(begainFullScreen) name:UIWindowDidBecomeVisibleNotification object:nil];//进入全屏
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];//退出全屏
}

-(void)begainFullScreen{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = NO;
    [self.bt setTitle:@"解除锁定" forState:UIControlStateNormal];
}

// 退出全屏
-(void)endFullScreen{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = YES;
    [self.bt setTitle:@"强制横屏" forState:UIControlStateNormal];
}

@end
